import { Button, Footer, Form, Input, NavBar, TextArea, Toast } from 'antd-mobile';
import './upsert.css';
import { useDispatch, useSelector } from 'react-redux';
import { listSlice } from '../../redux/slice/listSlice';
import { useNavigate, useParams } from 'react-router-dom';
import { useEffect } from 'react';
import { CardData } from '../../types/dataType';
import { FormInstance } from 'antd-mobile/es/components/form';
import React from 'react';

function Upsert() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { id } = useParams();
  const formRef = React.createRef<FormInstance>();
  const listData = useSelector((state: { list: CardData[] }) => state.list);
  useEffect(() => {
    if (id) {
      const currentItem = listData.find((item) => item.id === Number(id));
      if (currentItem) {
        formRef.current?.setFieldsValue({
          title: currentItem.title,
          content: currentItem.content
        });
      }
    }
  }, [id]);

  const onFinish = (values: { title: string; article: string }) => {
    if (id) {
      dispatch(listSlice.actions.update({ id: Number(id), ...values }));
      Toast.show('编辑成功');
    } else {
      dispatch(listSlice.actions.add({ id: Math.floor(Math.random() * 10000), ...values }));
      Toast.show('添加成功');
    }

    navigate('/');
  };
  const back = () => {
    navigate('/');
  };
  return (
    <>
      <NavBar onBack={back}>{id ? '编辑页面' : '添加页面'}</NavBar>
      <div className="main-container">
        <Form
          layout="horizontal"
          ref={formRef}
          onFinish={onFinish}
          footer={
            <Button block type="submit" color="primary" size="large">
              提交
            </Button>
          }
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '标题不能为空' }]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>
          <Form.Item name="content" label="正文" help="正文">
            <TextArea placeholder="请输入正文" maxLength={100} rows={2} showCount />
          </Form.Item>
        </Form>
      </div>
      <Footer content="@ LeeYa Developed"></Footer>
    </>
  );
}

export default Upsert;
